/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * SelectFiles.java
 *
 * Created on 31/08/2011, 13:49:11
 */

package ufpb.compiladores.lexico.run.GUI;

import java.io.File;
import java.util.Vector;
import javax.swing.filechooser.FileFilter;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import org.w3c.dom.Document;
import ufpb.compiladores.lexico.Automaton;
import ufpb.compiladores.lexico.AutomatonFactory;
import ufpb.compiladores.lexico.Enviroment;
import ufpb.compiladores.lexico.LexicalTable;
import ufpb.compiladores.lexico.Reader;
import ufpb.compiladores.lexico.XMLLoader;
import ufpb.compiladores.sintatico.SyntacticalAnalyzer;
import ufpb.compiladores.sintatico.SyntacticalAnalyzerFactory;

/**
 *
 * @author Sarah
 */
public class SelectFiles extends javax.swing.JFrame {


    private Vector caminhoAux = new Vector();
    private Vector caminho = new Vector();
    private Vector v = new Vector();
    //StringBuilder caminho;
    //StringBuilder caminhoAux;
    private String caminhoXML;
    private String syntacticaConf = null;
    private int i=-1, j=-1;
    private boolean syntactical = false;

    /** Creates new form SelectFiles */
    public SelectFiles(boolean syntactical) {  
        
        this.syntactical = syntactical;
        initComponents();
        if (!syntactical) {
            
            this.remove(this.jLabel4);
            this.remove(this.jTextField3);
            this.remove(this.jButton5);
        }
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    /*public SelectFiles(Document[] doc, File[] file) throws IOException{

        CallTables t = new CallTables(doc, file);
        t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        t.setVisible(true);
        
    }*/

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jTextField3 = new javax.swing.JTextField();
        jButton5 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel1.setText("Arquivo de configuração para o analisador léxico");

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel2.setText("Arquivos para análise");

        jButton1.setFont(new java.awt.Font("Tahoma", 0, 14));
        jButton1.setText("Processar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jButton2.setText("Browse");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jTextField1.setFont(new java.awt.Font("Tahoma", 0, 14));

        jTextField2.setFont(new java.awt.Font("Tahoma", 0, 14));

        jList1.setFont(new java.awt.Font("Tahoma", 0, 14));
        jScrollPane1.setViewportView(jList1);

        jButton3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jButton3.setText("Browse");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setFont(new java.awt.Font("Tahoma", 0, 14));
        jButton4.setText("Adicionar");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 18));
        jLabel3.setText("Selecionar Arquivos");

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel4.setText("Arquivo de configuração para o analisador sintático");

        jTextField3.setFont(new java.awt.Font("Tahoma", 0, 14));

        jButton5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jButton5.setText("Browse");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 640, Short.MAX_VALUE)
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 474, Short.MAX_VALUE)
                                        .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 474, Short.MAX_VALUE)
                                        .addComponent(jTextField3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 474, Short.MAX_VALUE))
                                    .addGap(18, 18, 18)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(layout.createSequentialGroup()
                                            .addComponent(jButton3)
                                            .addGap(9, 9, 9)
                                            .addComponent(jButton4))
                                        .addComponent(jButton2)
                                        .addComponent(jButton5)))
                                .addComponent(jLabel1)
                                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addContainerGap())
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addComponent(jButton1)
                            .addGap(276, 276, 276))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel4)
                            .addGap(279, 279, 279)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addGap(209, 209, 209))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addGap(17, 17, 17)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton4)
                    .addComponent(jButton3)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 162, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addGap(46, 46, 46))
        );

        jLabel1.getAccessibleContext().setAccessibleName("Arquivo de configuração para o analisador léxico");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        JFileChooser fc = new JFileChooser();
        MyFileFilter filter = new MyFileFilter();
        fc.setFileFilter(filter);

       // fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int returnVal = fc.showOpenDialog(null);

            if(returnVal == JFileChooser.APPROVE_OPTION) {
            File arquivo = fc.getSelectedFile();
            jTextField1.setText("" + arquivo.getAbsolutePath());
            caminhoXML = arquivo.getAbsolutePath();
            }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        i+=1;
        JFileChooser fc = new JFileChooser();
        int returnVal = fc.showOpenDialog(null);
 
            if(returnVal == JFileChooser.APPROVE_OPTION) {
                File arquivo = fc.getSelectedFile();
                jTextField2.setText("" + arquivo.getAbsolutePath());
                caminhoAux.add(arquivo.getAbsolutePath());
            }
            //JOptionPane.showMessageDialog(this, "Erro.");
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        
         if(!jTextField2.getText().equals("")){

            j+=1;
            v.add(jTextField2.getText());
            jTextField2.setText("");
            jList1.setListData(v);
            caminho=caminhoAux;
        }
        else {
           JOptionPane.showMessageDialog(this, "Localize pelo menos um arquivo para adicionar.");
        }
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

        try {
            
            //Se a lista tiver vazia
            StringBuilder errmsg = new StringBuilder();
            boolean err = false;
            if(0 == jList1.getModel().getSize())
            {

                errmsg.append("Adicione, pelo menos, um arquivo para processar\n");
                err = true;
            }

            if(null == caminhoXML)
            {
                errmsg.append("Adicione o arquivo de configuração do léxico.\n");
                err = true;
            }

            if (this.syntacticaConf == null && this.syntactical) {

                errmsg.append("Adicione o arquivo de configuração do sintático.");
                err = true;
            }

            if (err) {

                JOptionPane.showMessageDialog(this, errmsg.toString(),
                        "Error", JOptionPane.ERROR_MESSAGE);
                return;
            }

            Document[] docs = new Document[jList1.getModel().getSize()];
            File[] files = new File[docs.length];
            XMLLoader loader = new XMLLoader(caminhoXML);
            Enviroment env = null;
            env = loader.createEnviroment();
            
            Document doc = null;
            LexicalTable[] lt = new LexicalTable[docs.length];
            SyntacticalAnalyzer[] sa = null;
            ufpb.compiladores.sintatico.Enviroment senv = null;
            if (this.syntactical) {

                ufpb.compiladores.sintatico.XMLLoader sload = 
                                new ufpb.compiladores.sintatico.XMLLoader(new File(this.syntacticaConf));
                        senv = sload.createEnviroment();
                sa = new SyntacticalAnalyzer[docs.length];
            }

            for (int k = 0; k < docs.length; k++){

                //files[1] = new File((String)jList1.getModel().getElementAt(1));
                files[k] = new File((String)caminho.get(k));
                Reader r = null;
                r = new Reader(files[k].toString());
                Automaton auto = AutomatonFactory.getAutomaton(env, r);

                docs[k].createElement("Raiz");
                lt[k] = auto.generateTable(docs[k], docs[k].getDocumentElement());

                if (this.syntactical) {

                    sa[k] = SyntacticalAnalyzerFactory.createSyntacticalAnalyzer(senv, lt[k]);
                }
            }

            this.dispose();
            /*if (this.syntactical) {
                
                (new CallTables(sa, docs, files)).setVisible(true);
            } else {
                
                (new CallTables(docs, files)).setVisible(true);
            }*/
        } catch (Exception e) {
            
            e.printStackTrace();
        }

    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        
        JFileChooser fc = new JFileChooser();
        int returnVal = fc.showOpenDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            
            File arquivo = fc.getSelectedFile();
            jTextField3.setText(arquivo.getAbsolutePath());
            this.syntacticaConf = arquivo.getAbsolutePath();
        }
    }//GEN-LAST:event_jButton5ActionPerformed

    private class MyFileFilter extends FileFilter{

        @Override
        public boolean accept(File pathname) {

            if((pathname.getName().endsWith("xml"))|| pathname.isDirectory()){
                return true;
            }
            else {
                return false;
            }
        }


        @Override
        public String getDescription() {
            return ("Arquivo de configuração xml");
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JList jList1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    // End of variables declaration//GEN-END:variables

}
